import ujson as json
from django.db import transaction

from base import errors
from base import controllers as base_ctl
from account.models import SettingModel
from utils import time_utils


def create_setting(name, path):
    '''
    创建常用配置
    '''
    obj = SettingModel.objects.filter(path=path).first()
    if obj:
        raise errors.CommonError('配置已经存在')
    data = {
        'name': name,
        'path': path,
    }
    base_ctl.create_obj(SettingModel, data)


def update_setting(obj_id, name, path):
    '''
    编辑常用配置
    '''
    obj = base_ctl.get_obj(SettingModel, obj_id)
    data = {
        'name': name,
        'path': path,
    }
    base_ctl.update_obj(SettingModel, obj_id, data)


def delete_setting(obj_id):
    '''
    删除常用配置
    '''
    SettingModel.objects.filter(id=obj_id).delete()


def get_settings(page_num=None, page_size=None):
    '''
    获取配置列表
    '''
    base_query = SettingModel.objects
    total = base_query.count()
    objs = base_ctl.query_objs_by_page(base_query, page_num, page_size)
    data_list = []
    for obj in objs:
        data = obj.to_dict()
        data_list.append(data)
    data = {
        'total': total,
        'data_list': data_list,
    }
    return data


def get_setting(obj_id):
    '''
    获取配置信息
    '''
    obj = base_ctl.get_obj(SettingModel, obj_id)
    data = obj.to_dict()
    return data